package bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author chenyuan
 * @date 2020/10/31 10:08
 */
public class BIOServer {
	public static void main(String[] args) throws IOException {
		// 1. 创建一个线程池
		ExecutorService threadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
				60L, TimeUnit.SECONDS,
				new SynchronousQueue<Runnable>());
		// 监听“6666” 端口，接收客户连接请求，并生成与客户端连接的Socket
		ServerSocket serverSocket = new ServerSocket(6666);

		System.out.println("服务器启动了");

		while (true) {
			// 监听，等待客户端连接
			final Socket socket = serverSocket.accept();
			System.out.println("连接到一个客户端");

			// 2. 如果有客户端连接，就创建一个线程，与之通信
			threadPool.execute(() -> {
				handler(socket);
			});
		}
	}

	/**
	 * 和客户端通信的方法
	 * 循环的读取客户端的数据，然后输出
	 */
	public static void handler(Socket socket) {
		// 打印线程信息
		System.out.println("线程信息：{id：" + Thread.currentThread().getId() + ", " +
				"name: " + Thread.currentThread().getName());
		// 用于接收数据
		byte[] bytes = new byte[1024];
		// 通过 socket 获取输入流
		try {
			InputStream inputStream = socket.getInputStream();

			// 循环的读取客户端发送的数据
			while (true) {
				System.out.println("进行通信线程信息：{id：" + Thread.currentThread().getId() + ", " +
						"name: " + Thread.currentThread().getName());
				int read = inputStream.read(bytes);
				if (read != -1) {
					// 说明还可以读
					// 输出客户端发送的数据
					System.out.println(new String(bytes, 0, read));
				} else {
					// 读取完毕
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			System.out.println("关闭连接");
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
